layui.use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    form.on("submit(add)", function (data) {
        var jsondata = {
            menuId: $("#menuId").val(),
            name: $("#name").val(),
            parentId: $("#parentId").val(),
            url: $("#url").val(),
            perms: getPerms(),
            orderNum: $("#orderNum").val(),
            type: $("#type").val()
        };
        $.ajax({
            type: 'post',
            url: "/admin/sys/menu/save.do",
            async : false,
            data: JSON.stringify(jsondata),
            success: function (res) {
                if (res.code == 0) {
                    top.layer.msg("操作成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                    form.render();
                } else {
                    layer.msg(res.msg);
                }
            },
            contentType: 'application/json;charset=utf-8',
            dataType: 'json'
        });
    });

    function getPerms() {
        var perms = "";
        $("input[type='checkbox']:checked").each(function (i) {
            if (i == 0) {
                perms = $(this).val();
            } else {
                perms = perms + "," + $(this).val();
            }
        });
        return perms;
    };

    //初始化数据
    function loadData() {
        var id = getQueryString("id");
        form.render();
        if (id) {
            $.ajax({
                type: 'GET',
                async: false,
                url: "/admin/sys/menu/get/" + id + ".do",
                success: function (res) {
                    var menu = res.data;
                    $("#menuId").val(menu.menuId);
                    $("#parentId").val(menu.parentId);
                    $("#name").val(menu.name);
                    $("#url").val(menu.url);
                    $("#orderNum").val(menu.orderNum);
                    $("#type").val(menu.type);
                    initPerms(menu.perms);
                    form.render();
                }
            })
        }
    }

    //获取url后参数值
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    function initPerms(perms) {
        if(perms){
            $("input[type='checkbox']").each(function (i) {
                var  perm = $(this).val();
                if(perms.indexOf(perm) != -1){
                    $(this).attr("checked", 'checked');
                }
            });
        }
    }
    loadData();

});
